from collections import Counter
from datetime import datetime

import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt

from utils.MysqlConnect import MysqlConnect


def getWordCloud():
    mysql = MysqlConnect()
    # 获取当前日期
    current_date = datetime.now().strftime('%Y-%m-%d')
    query_sql = f"select hot_keyword,top_count from analysis where platform = '微博' and date_format(end_time,'%Y-%m-%d') = '{current_date}' order by top_count desc"
    data = mysql.query(query_sql)

    # 提取关键词并计算词频
    all_keywords = " ".join([row[0] for row in data])
    words = jieba.cut(all_keywords)
    word_freq = Counter(words)

    # 生成云词图，指定字体文件
    wordcloud = WordCloud(
        width=1600,  # 词云图宽度
        height=800,  # 词云图高度
        background_color=None,  # 背景颜色
        font_path='msyh.ttc',  # 字体文件路径（确保字体文件路径正确）
        max_words=2000,  # 设置最大词数
        min_font_size=10,  # 设置最小字体大小
        colormap='viridis',  # 设置配色方案
        random_state=42  # 设置随机状态，保证每次生成的结果一致
    ).generate_from_frequencies(word_freq)

    # 绘制并保存图片
    plt.figure(figsize=(16, 8))  # 设置图像尺寸
    plt.imshow(wordcloud, interpolation='bilinear')  # 显示词云图
    plt.axis('off')  # 关闭坐标轴
    plt.tight_layout(pad=0)
    plt.savefig('./png/weibo_wordcloud.png', dpi=300)  # 保存图片为 weibo_wordcloud.png，设置dpi参数提高分辨率
    plt.show()  # 显示词云图


if __name__ == '__main__':
    getWordCloud()
